package com.shuoyutech.dp.common.framework.exception;

import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelCommonException;
import com.shuoyutech.dp.common.framework.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author dyb
 * @date 2021/2/25
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public Result handleException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return Result.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 异常
     */
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error("服务器错误，请联系管理员");
    }

    /**
     * 运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public Result runtimeException(Exception e) {
        log.error("运行时异常:", e);
        return Result.error("运行时异常:" + e.getMessage());
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result businessException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public Result validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return Result.error(message);
    }

    /**
     * excel解析异常
     */
    @ExceptionHandler(ExcelAnalysisException.class)
    public Result excelAnalysisException(ExcelAnalysisException e) {
        log.error(e.getMessage(), e);
        return Result.error("模板解析失败，请核对后重试");
    }

    /**
     * 上传文件转为excel失败
     */
    @ExceptionHandler(ExcelCommonException.class)
    public Result excelCommonException(ExcelCommonException e) {
        log.error(e.getMessage(), e);
        return Result.error("模板解析失败，请使用系统提供模板");
    }


}
